﻿using Elio.Controls;
using Elio.Interfaces;
using Elio.Sessions;
using Elio.Sessions.Widgets;
using Google.Protobuf.WellKnownTypes;

namespace Elio.Widgets;

public class WidgetEditor : Editor, ISessionWidget
{
    public BaseSession? Session { get; set; }
    public void Init(InitOptions options)
    {
        (WidthRequest, HeightRequest) = (options.Width, options.Height);
        this.SetPoint(options.X, options.Y);
        Text = options.Text;
    }

    public async Task<bool> OnViewReceive(string name, long sid, long fid, params Any[] argv)
    {
        switch (name)
        {
            case "getHint":
                await GetHint(sid, fid);
                break;

            case "setHint":
                SetHint(argv);
                break;

            case "isInputPhone":
                await IsInputPhone(sid, fid);
                break;

            case "setInputPhone":
                SetInputPhone();
                break;

            case "isInputNumber":
                await IsInputNumber(sid, fid);
                break;

            case "setInputNumber":
                SetInputNumber();
                break;

            case "getText":
                await GetText(sid, fid);
                break;

            case "setText":
                SetText(argv);
                break;

            default:
                return false;
        }
        return true;
    }

    private async Task GetHint(long sid, long fid)
    {
        string hint = Placeholder ?? string.Empty;
        await Session!.SendAction("onGetHint", sid, fid, hint.ToAny());
    }

    private void SetHint(params Any[] argv) =>
        Placeholder = argv[0].P2String();

    private async Task IsInputPhone(long sid, long fid)
    {
        // TODO
        bool res = false;
        await Session!.SendAction("onIsInputPhone", sid, fid, res.ToAny());
    }

    private static void SetInputPhone() { }

    private async Task IsInputNumber(long sid, long fid)
    {
        // TODO
        bool res = false;
        await Session!.SendAction("onIsInputNumber", sid, fid, res.ToAny());
    }

    private static void SetInputNumber() { }

    private async Task GetText(long sid, long fid) =>
        await Session!.SendAction("onGetText", sid, fid, Text.ToAny());

    private void SetText(params Any[] argv) => Text = argv[0].P2String();
}
